import json
import uuid

from django.contrib.auth import authenticate
from django.core.cache import cache
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render

# Create your views here.
def login(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        username = data.get('username')
        password = data.get('password')
        user = authenticate(username=username, password=password)
        if user:
            token = uuid.uuid4().hex
            cache.set(token, user.id)
            data = {
                'username': username,
                'password': password,
                'token': token
            }
            res = {
                'data': data,
                'meta': {'status': 200, 'message': '登录成功！'}
            }
        else:
            res = {
                'data': None,
                'meta': {'status': 801, 'message': '用户名或密码错误'}
            }
    else:
        res = {
            'data': None,
            'meta': {'status': 802, 'message': '仅接收POST请求'}
        }
    return JsonResponse(res)


def logout(request):
    token = request.META.get("HTTP_AUTHORIZATION")
    print(token)
    cache.delete(token)
    res = {
        'data': {},
        'meta': {'status': 200, 'message': '退出登录成功'}
    }
    return JsonResponse(res)


def change_password(request):
    if request.method == 'PUT':
        data = json.loads(request.body)
        username = data.get('username')
        password = data.get('password')
        new_password = data.get('newPassword')
        user = authenticate(username=username, password=password)
        if user:
            user.set_password(new_password)
            user.save()
            res = {
                'data': {'username': username},
                'meta': {'status': 200, 'message': '修改密码成功！'}
            }
        else:
            res = {
                'data': {'username': username},
                'meta': {'status': 201, 'message': '用户名或密码错误'}
            }
        return JsonResponse(res)